package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;

    //验证码发送成功后将验证码保存到redis中,因为只需要验证码几分钟内有效即可,所以不需要保存到mysql中
    @RequestMapping("/send4Order")
    public Result sen4Order(String telephone){
        Jedis jedis = jedisPool.getResource();
        //调用工具类获取4位验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        //给用户发送短信验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //验证码发送失败,直接结束方法,不用存进redis中
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //验证码发送成功,保存到redis仓库中,时间单位是s
        jedis.setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,300,validateCode.toString());
        jedis.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    /**
     * 手机验证码快速登录
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        Jedis jedis = jedisPool.getResource();
        //生成验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(6);
        //发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //将验证码保存到redis中,定时清除
        jedis.setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN,300,validateCode.toString());
        jedis.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
